#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from django.http.response import HttpResponse
from django.utils.dateparse import parse_date
from xls_demo.db import models
from xls_demo.utils import create_failure_dict
from xls_demo.utils import RevisedDjangoJSONEncoder


class JsonResponseMiddleware(object):
    def process_response(self, request, response):
        if isinstance(response, dict):
            data = json.dumps(response, cls=RevisedDjangoJSONEncoder)
            if 'callback' in request.REQUEST:
                data = '%s(%s);' % (request.REQUEST['callback'], data)
                return HttpResponse(data, "text/javascript")
            # return HttpResponse(data, "application/json")
            # IE会对json response弹出下载文件框，所以不使用application/json
            return HttpResponse(data)
        else:
            return response

# MH:banbantong.Middleware
class ValidateDateRangeMiddleware(object):
    '''处理Request中的时间范围，
        1. 如果都不存在，就设定为当前学期
        2. 检查start_date和end_date
        3. 检查school_year和term_type
        4. 如果开始时间超过学期边界，就对齐到最近的学期开始时间
        5. 如果结束时间超过学期边界，就对齐到最近的学期结束时间
        6. 如果时间范围超过一个学期，就报错
    '''

    def check_date(self, request):
        start_date = request.GET.get('start_date')
        end_date = request.GET.get('end_date')
        request.GET = request.GET.copy()
        s = parse_date(start_date)
        e = parse_date(end_date)
        # 1. 开始时间在某个学期内
        q = models.Term.objects.filter(start_date__lte=s, end_date__gte=s)
        if q.exists():
            t1 = q[0]
        else:
            # 2. 如果开始时间不在学期内，就使用最近的下一个学期开始时间
            q = models.Term.objects.filter(start_date__gte=s)
            q = q.order_by('start_date')
            if q.exists():
                t1 = q[0]
                request.GET['start_date'] = str(t1.start_date)
            else:
                return create_failure_dict(msg='开始时间不在任何学期内')
        # 3. 结束时间在某个学期内
        q = models.Term.objects.filter(start_date__lte=e, end_date__gte=e)
        if q.exists():
            t2 = q[0]
        else:
            # 4. 如果结束时间不在学期内，就使用最近的上一个学期结束时间
            q = models.Term.objects.filter(end_date__lte=e)
            q = q.order_by('-end_date')
            if q.exists():
                t2 = q[0]
                request.GET['end_date'] = str(t2.end_date)
            else:
                return create_failure_dict(msg='结束时间不在任何学期内')
        # 5. 开始时间与结束时间不在同一学期
        if t1 != t2:
            return create_failure_dict(msg='开始时间与结束时间不在学期内')

    def process_request(self, request):
        if request.method != 'GET':
            return
        if models.Setting.getvalue('server_type') not in ('school', 'country'):
            return
        if request.path.startswith('/activity/'):  # 使用记录
            if 'start_date' not in request.GET and 'end_date' not in request.GET:
                return
            start_date = request.GET.get('start_date')
            end_date = request.GET.get('end_date')
            if not start_date and not end_date:
                msg = '请选择时间范围（时间范围必须在一个学期内）'
                return create_failure_dict(msg=msg)
            return self.check_date(request)
        elif request.path.startswith('/statistic/'):  # 统计分析
            start_date = request.GET.get('start_date')
            end_date = request.GET.get('end_date')
            school_year = request.GET.get('school_year')
            term_type = request.GET.get('term_type')
            if start_date and end_date:
                return self.check_date(request)
            elif school_year and term_type:
                return
            else:
                return create_failure_dict(msg='只能查询一个学期内的数据')
        else:
            return
